﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace SharedLib.Helpers
{
    public class RegistryHelper
    {
        public static List<string> GetOpenWithList(string fileExt)
        {
            List<string> rtn = new List<string>();
            if (String.IsNullOrEmpty(fileExt)) return rtn;
            string ext = fileExt;
            if (!ext.StartsWith(".")) ext = "." + ext;
            RegistryKey extKey = Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Explorer").OpenSubKey("FileExts").OpenSubKey(ext);
            if (extKey != null)
            {
                RegistryKey openWithKey = extKey.OpenSubKey("OpenWithList");
                if (openWithKey != null)
                {
                    //Navigate to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{.fileExt}\OpenWithList
                    string mruList = openWithKey.GetValue("MRUList") as string;
                    if (mruList != null)
                    {
                        foreach (char c in mruList)
                        {
                            string appName = openWithKey.GetValue(c.ToString()) as string;
                            if (!String.IsNullOrEmpty(appName))
                            {
                                //Navigate to HKEY_CLASSES_ROOT\Applications\{appName}
                                RegistryKey appKey = Registry.ClassesRoot.OpenSubKey("Applications").OpenSubKey(appName);
                                if (appKey != null)
                                {
                                    RegistryKey tmpKey = appKey.OpenSubKey("shell");
                                    if(tmpKey != null){
                                        tmpKey = tmpKey.OpenSubKey("open");
                                        if(tmpKey != null){
                                            tmpKey = tmpKey.OpenSubKey("command");
                                            if (tmpKey != null)
                                            {
                                                string appPath = tmpKey.GetValue(null) as string;
                                                if (!String.IsNullOrEmpty(appPath)) rtn.Add(appPath);
                                            }
                                        }
                                    }
                                    
                                }
                            }
                        }
                    }
                }
            }
            return rtn;
        }
    }
}
